package com.web.template;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Bootstrap {


  private static volatile Bootstrap daemon = null;

  private Object catalinaDaemon = null;
  ClassLoader catalinaLoader = null;

  public static void main(String[] args) throws Exception {

    Bootstrap bootstrap = new Bootstrap();
    try {
      bootstrap.init();
    } catch (Throwable t) {
      t.printStackTrace();
      return;
    }
    daemon = bootstrap;

    String command = "start";
    if (args.length > 0) {
      command = args[args.length - 1];
    }
    if (command.equals("startd")) {
      args[args.length - 1] = "start";
      daemon.load(args);
      daemon.start();
    } else if (command.equals("start")) {
      daemon.load(args);
      daemon.start();
    }
  }

  public void init() {
    Class<?> startupClass = null;
    try {
      catalinaLoader = this.getClass().getClassLoader();
      startupClass = catalinaLoader.loadClass("com.web.template.Catalina");
      catalinaDaemon = startupClass.getConstructor().newInstance();
    } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
      e.printStackTrace();
    }
  }

  private void load(String[] arguments) {

    String methodName = "load";

    Method method = null;
    try {
      method = catalinaDaemon.getClass().getMethod(methodName);
      method.invoke(catalinaDaemon);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
      e.printStackTrace();
    }

  }

  public void start() throws Exception {
    if (catalinaDaemon == null) {
      init();
    }

    Method method = catalinaDaemon.getClass().getMethod("start", (Class[]) null);
    method.invoke(catalinaDaemon, (Object[]) null);
  }

}
